package com.chs.recoginition.core.utils;

import com.chs.recoginition.core.exception.ApplicationException;
import com.chs.recoginition.core.exception.constant.ExceptionConstant;
import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Collection;

/**
 * 断言工具
 *
 */
public class AssertHelper {

    public static void assertTrue(Boolean condition, String message) {
        if (condition == null || !condition) {
            throw new ApplicationException(ExceptionConstant.ILLEGAL_PARAM, message);
        }
    }

    public static void assertFalse(Boolean condition, String message) {
        if (condition == null || condition) {
            throw new ApplicationException(ExceptionConstant.ILLEGAL_PARAM, message);
        }
    }

    public static void notNull(Object object, String message) {
        if (object == null) {
            throw new ApplicationException(ExceptionConstant.PARAM_NOT_NULL, message);
        }
    }

    public static void idlegal(Integer object, String message) {
        if (object == null || object == 0) {
            throw new ApplicationException(ExceptionConstant.PARAM_NOT_NULL, message);
        }
    }

    public static void notBlank(String string, String message) {
        if (StringUtils.isBlank(string)) {
            throw new ApplicationException(ExceptionConstant.PARAM_NOT_NULL, message);
        }
    }

    public static void notEmpty(Object[] arr, String message) {
        if (arr == null || arr.length == 0) {
            throw new ApplicationException(ExceptionConstant.PARAM_NOT_NULL, message);
        }
    }

    public static void notEmpty(Collection collection, String message) {
        if (collection == null || collection.isEmpty()) {
            throw new ApplicationException(ExceptionConstant.PARAM_NOT_NULL, message);
        }
    }

    /**
     * 断言：合法日期格式
     */
    public static void formatLegal(String dateStr, String pattern, String message) {
        if (!formatSuccess(dateStr, pattern)) {
            throw new ApplicationException(ExceptionConstant.ILLEGAL_PARAM, message);
        }
    }

    private static boolean formatSuccess(String dateStr, String pattern) {
        if (dateStr == null) {
            return false;
        }

        try {
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            sdf.parse(dateStr);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

}
